package com.jt.service;

import com.jt.vo.ImageVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Author Yu
 * @create 2025/07/08
 * @description
 */
@Service
@PropertySource("classpath:/image.properties")
public class FileServiceImpl implements FileService{

    @Value("${image.localPathDir}")
    private String localPathDir;
    @Value("${image.localUrlPath}")
    private String localUrlPath;


    @Override
    public ImageVo upload(MultipartFile file) throws IOException {
        // 获取图片名称
        String fileName = file.getOriginalFilename();
        // 将图片名称转换为全小写
        fileName = fileName.toLowerCase();
        // 正则表达式校验图片类型是否正确
        if(!fileName.matches("^.+\\.(jpg|png|gif)$")){
            return null;
        }
        // 判断是否为木马文件
        try {
            BufferedImage readFile = ImageIO.read(file.getInputStream());
            int width = readFile.getWidth();
            int height = readFile.getHeight();
            if (width==0 || height==0){
                return null;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 图片路径拼接   /2025/7/8/
        String dateFile =
                new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
        // 存储真实路径 进行目录的拼接  "D:/JT_IMAGE/2021/11/11";
        String localDir = localPathDir + dateFile;
        File file1 = new File(localDir);
        /*判断当前路径存不存在 不存在则直接创建*/
        if (!file1.exists()){
            file1.mkdirs();
        }
        // 拼接图片名字并替换  uuid.png
        String uuidFileName =
                UUID.randomUUID().toString().replace("-", "");
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        //uuid.png
        String realName = uuidFileName + fileType;
        // 图片上传  "D:/JT_IMAGE/2021/11/11/uuid.png"
        String uploadPath = localDir + realName;
        File file2 = new File(uploadPath);
        file.transferTo(file2);
        String virPath = dateFile + realName;
        //http://image.jt.com/2021/11/11/uuid.jpg
        String urlPath = localUrlPath + virPath;
        return new ImageVo(virPath,urlPath,realName);
    }

    @Override
    public void deleteFile(String virtualPath) {
        // D:/JT_IMAGE/2025/7/8/uuid.png
        String realPath = localPathDir + virtualPath;
        File file = new File(realPath);
        file.delete();
    }
}
